package com.zilu.digitaltwin.common.response;

import com.zilu.digitaltwin.common.constants.CommonConstants;
import com.zilu.digitaltwin.common.enums.ResponseCodeEnum;
import lombok.Data;
import org.slf4j.MDC;

@Data
public class Response<T> {
    private int code;
    private String msg;
    private T data;
    private String requestId;

    private Boolean isError = false;

    private Response(int code, String msg, T data, String requestId) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.requestId = requestId;
    }

    private Response(int code, String msg, T data, String requestId, boolean isError) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.requestId = requestId;
        this.isError = isError;
    }


    public static Response<ResDataEmpty> success() {
        return new Response<>(ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getMsg(), null, MDC.get(CommonConstants.REQ_ID));
    }

    public static <T> Response<T> success(T data) {
        return new Response<>(ResponseCodeEnum.SUCCESS.getCode(), ResponseCodeEnum.SUCCESS.getMsg(), data, MDC.get(CommonConstants.REQ_ID));
    }

    public static Response<ResDataEmpty> failed(String msg) {
        return new Response<>(ResponseCodeEnum.FAILED.getCode(), msg, null, MDC.get(CommonConstants.REQ_ID), true);
    }

    public static Response<ResDataEmpty> custom(ResponseCodeEnum errorCodeEnum) {
        return new Response<>(errorCodeEnum.getCode(), errorCodeEnum.getMsg(), null, MDC.get(CommonConstants.REQ_ID), isError(errorCodeEnum.getCode()));
    }

    public static Response<ResDataEmpty> custom(int code, String msg) {
        return new Response<>(code, msg, null, MDC.get(CommonConstants.REQ_ID),isError(code));
    }

    public static <T> Response<T> custom(int code, String msg, T data) {
        return new Response<>(code, msg, data, MDC.get(CommonConstants.REQ_ID), isError(code));
    }

    private static boolean isError(int code) {
        return ResponseCodeEnum.SUCCESS.getCode() == code ? true : false;
    }
}
